昨天我們學會了如何把專案結構整理乾淨。
但一個專案隨著重構、功能新增,最常見的問題就是:改了一個地方,壞了另外一個地方。
今天的目標,就是要讓專案開始具備「保護自己」的能力 —— 自動化測試(Testing)。
想像一下情境:
auth
模組重構了,結果登入壞掉了。posts
新增了 API,但不小心回傳型別錯誤。測試就是一種 保險:
calculatePrice()
是否回傳正確數字。user
狀態是否正確更新。# 安裝測試套件
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
建立 jest.config.js
:
module.exports = {
testEnvironment: "jsdom",
setupFilesAfterEnv: ["@testing-library/jest-dom"],
}
假設有一個按鈕:
// shared/components/Button.tsx
export function Button({ label }: { label: string }) {
return <button>{label}</button>
}
測試它是否正確渲染:
// shared/components/Button.test.tsx
import { render, screen } from "@testing-library/react"
import { Button } from "./Button"
test("renders button with label", () => {
render(<Button label="Click Me" />)
expect(screen.getByText("Click Me")).toBeInTheDocument()
})
執行測試:
npm run test
結果會顯示:
✅ renders button with label
你甚至可以直接請 Cursor 幫你寫測試:
幫 Button.tsx 產生對應的 Jest 測試
或:
幫 useAuth hook 建立單元測試,模擬 login API 成功與失敗的情境
Cursor 會自動產生測試檔案,讓你快速有個基礎測試可以跑。
新的習慣:
甚至可以設定 CI/CD(例如 GitHub Actions),讓每次 Push 自動跑測試,出錯就不允許合併。
今天我們學會了: